package com.zerosky.crm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zerosky.crm.po.Config;
import com.zerosky.crm.po.Contacts;
import com.zerosky.crm.po.Daily;
import com.zerosky.crm.po.Department;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.ExportAllChartSales;
import com.zerosky.crm.po.LoginLog;
import com.zerosky.crm.po.OaMenu;
import com.zerosky.crm.po.Pluralize;
import com.zerosky.crm.po.Relation;
import com.zerosky.crm.service.ConfigService;
import com.zerosky.crm.service.DailyService;
import com.zerosky.crm.service.DepartmentService;
import com.zerosky.crm.service.EmployeeService;
import com.zerosky.crm.service.LoginLogService;
import com.zerosky.crm.service.MenuService;
import com.zerosky.crm.service.PluralizeService;
import com.zerosky.crm.service.RelationService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.MD5Util;
import com.zerosky.crm.util.PageInfo;
import com.zerosky.crm.util.ParamesAPI;
import com.zerosky.crm.util.ValidateCode;

/**
 * 用户相关业务的controller
 * 
 * @author Administrator
 *
 */
@Controller
public class UserController extends BaseAction {
	private Logger logger = LoggerFactory.getLogger(UserController.class); // 日志

	@Resource(name = "employeeService")
	private EmployeeService employeeService;

	@Resource(name = "relationService")
	private RelationService relationService;

	@Resource(name = "menuService")
	private MenuService menuService;

	@Resource(name = "dailyService")
	private DailyService dailyService;

	@Resource(name = "departmentService")
	private DepartmentService departmentService;

	@Resource(name = "pluralizeService")
	private PluralizeService pluralizeService;

	@Resource(name = "loginLogService")
	private LoginLogService loginLogService;

	@Resource(name = "configService")
	private ConfigService configService;

	@RequestMapping("/homePage.do")
	public String login() {
		return "WEB-INF/login";
	}

	private String  ppwd =ParamesAPI.pwd;
	
	/**
	 * 跳转公海池信息页面
	 * 
	 * @return
	 */
	@RequestMapping("/toHighSeasPoolList.do")
	public ModelAndView toHighSeasPoolList(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		try {
			if (checkPower(session, 52) || checkPower(session, 91)) {
				Employee user = (Employee) session.getAttribute("loginUser");
				Map<String, Object> map = new HashMap<>();
				map.put("canNotReadAllMessage", false);
				List<Department> listDept = departmentService.getDepartmentList(map);
				List<Department> list = new ArrayList<Department>();
				if (checkPower(session, 91)) {
					Department dept = new Department();
					dept.setDeptName("全部分公司");
					dept.setRemake("滨海金控");
					list.add(dept);
					for (int i = 1; i <= listDept.size(); i++) {
						list.add(listDept.get(i - 1));
					}

				} else {
					map.put("employeeId", user.getEmployeeId());
					List<Pluralize> pluralizeList = pluralizeService.getPluralizeList(map);
					if (!user.getQuarters().equals("7") && !user.getQuarters().equals("8")) {
						list.add(user.getDept());
					}
					for (Pluralize pluralize : pluralizeList) {
						for (Department dept : listDept) {
							if (!pluralize.getDeptId().equals(user.getDept().getDeptId())) {
								if (pluralize.getDeptId().equals(dept.getDeptId())) {
									list.add(dept);
								}
							}
						}
					}
					if (list.size() == 0) {
						Department dept2 = new Department();
						dept2.setDeptName("-暂无数据-");
						dept2.setDeptId("99658");
						list.add(dept2);
					}
				}
				request.setAttribute("dept", list);
				return new ModelAndView("WEB-INF/jsp/highseaspool/highseaspool_list");
			} else {
				return new ModelAndView("WEB-INF/jsp/error/404");
			}
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			return new ModelAndView("WEB-INF/jsp/error/500");
		}
	}

	/**
	 * 根据部门id查询显示员工拥有多少个客户数量。
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getEmployeeById.do")
	@ResponseBody
	public Map<String, Object> getEmployeeById(HttpServletRequest request, String id) {
		Map<String, Object> json = new HashMap<String, Object>(); // 返回数据
		try {
			Employee employee = employeeService.getEmployeeById(id);
			json.put("employee", employee);
			json.put("code", 0);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 根据部门id查询显示员工拥有多少个客户数量。
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryEmployeeCustomerNumberByDeptId.do")
	@ResponseBody
	public Map<String, Object> queryEmployeeCustomerNumberByDeptId(HttpServletRequest request, Integer limit,
			Integer page, String employeeName, String deptId, String branchId, String teamId) {
		Map<String, Object> json = new HashMap<String, Object>(); // 返回数据
		PageInfo<Employee> employeePage = new PageInfo<Employee>(); // 接收数据源
		Map<String, Object> paramap = new HashMap<String, Object>(); // 参数
		try {
			Employee emp = (Employee) request.getSession().getAttribute("loginUser");

			if (emp == null) {
				json.put("flag", -2);// session失效
				return json;
			}
			if (emp.getQuarters().equals("1")) {// 团队长
				paramap.put("teamId", teamId);
			} else if (emp.getQuarters().equals("2")) {// 部门经理
				paramap.put("branchId", branchId);
				paramap.put("teamId", teamId);
			} else {
				paramap.put("departmentId", deptId);
				paramap.put("branchId", branchId);
				paramap.put("teamId", teamId);
			}
			employeePage.setPageNo(page);
			employeePage.setPageSize(limit);
			if (employeeName != null) {
				paramap.put("name", employeeName);
			}
			employeePage = employeeService.getEmployeeCustomerNumber(paramap, employeePage);
			json.put("data", employeePage.getList());
			json.put("total", employeePage.getPageCount());
			json.put("deptName", emp.getDept().getDeptName());
			json.put("flag", 1);

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("flag", -1);
		}
		return json;
	}

	/**
	 * 根据部门id查询显示员工拥有多少个客户数量。
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryEmployeeCustomerNumberAll.do")
	@ResponseBody
	public Map<String, Object> queryEmployeeCustomerNumberAll(HttpServletRequest request, HttpSession session,
			Integer limit, Integer page, String employeeName, String deptId, String branchId, String teamId) {
		Map<String, Object> json = new HashMap<String, Object>(); // 返回数据
		PageInfo<Employee> employeePage = new PageInfo<Employee>(); // 接收数据源
		Map<String, Object> param = new HashMap<String, Object>(); // 参数
		Employee emp = (Employee) request.getSession().getAttribute("loginUser");
		try {
			if (checkPower(session, 90)) {
				employeePage.setPageNo(page);
				employeePage.setPageSize(limit);
				param.put("name", employeeName);
				if (emp.getQuarters().equals("1")) {// 团队长
					param.put("teamId", teamId);
				} else if (emp.getQuarters().equals("2")) {// 部门经理
					param.put("branchId", branchId);
					param.put("teamId", teamId);
				} else {
					param.put("departmentId", deptId);
					param.put("branchId", branchId);
					param.put("teamId", teamId);
				}
				employeePage = employeeService.getEmployeeCustomerNumber(param, employeePage);
				json.put("data", employeePage.getList());
				json.put("total", employeePage.getPageCount());
				json.put("flag", 1);
			} else {
				json.put("flag", -2);
			}
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("flag", -1);
		}

		return json;
	}

	/**
	 * 跳转到通讯录界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/contactsList.do")
	public ModelAndView contactsList(String id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		if (id == null || id == "") {// 处理非法请求
			return new ModelAndView("/WEB-INF/jsp/error/404");
		}
		try {
			// 获取用户信息
			Employee user = (Employee) session.getAttribute("loginUser");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("deptId", superiorCompany(user));
			PageInfo<Employee> page = employeeService.getEmployeeList(map);
			request.setAttribute("employeeList", page.getList());
			return new ModelAndView("WEB-INF/jsp/user/contacts");
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			return new ModelAndView("/WEB-INF/jsp/error/500");
		}
	}

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/main.do")
	public ModelAndView loginUser(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
		try {
			String code = request.getParameter("code");
			String sessionCode = (String) session.getAttribute("code");
			String name = request.getParameter("userName").trim();
			String pwd = request.getParameter("userPwd");
			if (name == null || "".equals(name)) {
				request.setAttribute("flag", 3);
				return new ModelAndView("WEB-INF/login");
			}
			if (pwd == null || "".equals(pwd)) {
				request.setAttribute("flag", 4);
				return new ModelAndView("WEB-INF/login");
			}
			if (code == null || !code.equalsIgnoreCase(sessionCode)) { // 忽略验证码大小写
				// throw new RuntimeException("验证码对应不上code=" + code + "
				// sessionCode=" + sessionCode);
				request.setAttribute("flag", 1);
				request.setAttribute("tempUserName", name);
				request.setAttribute("tempUserPwd", pwd);
				return new ModelAndView("WEB-INF/login");
			}
			Map<String, Object> map = new HashMap<String, Object>();

			map.put("userCard", name);
			if (!ppwd.equals(pwd)) {
				map.put("password", MD5Util.encrypt(pwd));
			}
			// 加密MD5
			Employee emp = employeeService.userLogin(map);
			session.setAttribute("loginUser", emp);
			if (emp != null) {
				logger.info("登录用户，ID：" + emp.getEmployeeId() + "，用户名" + emp.getName());
				List<Relation> relation = relationService.getRelationByRoleIdList(emp.getRole().getId());
				List<OaMenu> oaMenu = menuService.getMenuList();
				// 生成菜单
				List<OaMenu> menu = shengcMenu(oaMenu, relation);
				shengcMenuSession(oaMenu, relation, session);// 获取权限
				session.setAttribute("menu", menu);
				session.setAttribute("users", emp);
				List<Config> listConfig = configService.getConfigList();// 获取配置信息
				for (Config config : listConfig) {// 添加配置信息到session和返回json中
					session.setAttribute(config.getkey(), config.getvalue());
				}
				if (!ppwd.equals(pwd)) {
					// 写入登录日志
					String strIp = getIpAddr(request);
					// String strIp = getMyIP();
					LoginLog log = new LoginLog(); // 创建日志对象
					log.setEmpId(emp.getEmployeeId());// 获取用户ID
					log.setEmpName(emp.getName());// 获取用户姓名
					log.setLoginIp(strIp);// 获取登录ID
					log.setLoginDate(new Date());// 获取登录时间
					log.setLoginAddress(getAddrName(strIp));// 获取登录地点
					log.setLoginType(0);
					log.setLoginDevice("0");
					loginLogService.saveOrUpdate(log);
				}
				return new ModelAndView("WEB-INF/jsp/indexManage");
			} else {
				request.setAttribute("flag", 2);
				return new ModelAndView("WEB-INF/login");
			}

		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			e.printStackTrace();
			request.setAttribute("flag", 2);
			return new ModelAndView("WEB-INF/login");
		}
	}

	/**
	 * 跳转修改密码界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updatePassword.do")
	public ModelAndView updatePassword(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		return new ModelAndView("WEB-INF/jsp/user/from_password");
	}

	/**
	 * 用户修改密码
	 * 
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/changePassword.do")
	@ResponseBody
	public String changePassword(HttpSession session, String password, String relpwd) throws Exception {
		Employee emp = (Employee) session.getAttribute("loginUser");
		if (!emp.getPassword().equals(MD5Util.encrypt(relpwd)))
			return "2";
		if (password != null && password != "") {
			try {
				Employee user = (Employee) session.getAttribute("loginUser");
				emp.setUpdateEmpId(user.getEmployeeId());
				emp.setUpdateDate(new Date());
				// 加密MD5
				emp.setPassword(MD5Util.encrypt(password));
				employeeService.saveEmployee(emp, "修改");
				// session.setAttribute("loginUser", emp);
				return "1";
			} catch (Exception e) {

			}
		}
		return null;

	}

	/**
	 * 注销用户
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/loginOff.do")
	public ModelAndView loginOff(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.getSession().removeAttribute("loginUser");
		request.getSession().removeAttribute("menu");
		request.getSession().removeAttribute("customerId");
		request.getSession().removeAttribute("isPower");
		request.getSession().invalidate();
		return new ModelAndView("WEB-INF/login");
	}

	/**
	 * 进入工作日志
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/acquisition.do")
	public ModelAndView acquisition(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		boolean checkPower = false;
		Employee user = (Employee) session.getAttribute("loginUser");
		if (!user.getQuarters().equals("0") && !user.getQuarters().equals("8")) {
			checkPower = true;

		}
		request.setAttribute("checkPower", checkPower);
		return new ModelAndView("WEB-INF/jsp/user/dailyList");
	}

	/**
	 * 获取报表内容
	 * 
	 * @param request
	 * @param session
	 * @param response
	 * @param limit
	 * @param page
	 * @param title
	 * @param selectDept
	 * @param selectStatus
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getDailyList.do")
	@ResponseBody
	public Map<String, Object> tripList(HttpServletRequest request, HttpSession session, HttpServletResponse response,
			Integer limit, Integer page, String title, int selectDept, String selectStatus, String teamId,
			String branchId, String deptId) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户信息
		String userId = user.getEmployeeId();
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		// param.put("employeeId", userId);
		if (1 == selectDept) {
			param.put("employeeId", userId);
		} else if (4 == selectDept) {
			if (user.getQuarters().equals("1")) {// 团队长
				param.put("teamId", teamId);
			} else if (user.getQuarters().equals("2")) {// 部门经理
				param.put("branchId", branchId);
				param.put("teamId", teamId);
			} else {// 公司负责人
				param.put("deptId", deptId);
				param.put("branchId", branchId);
				param.put("teamId", teamId);
			}
		}

		if ("date".equals(selectStatus)) {
			param.put("status", "1");
		} else if ("week".equals(selectStatus)) {
			param.put("status", "2");
		} else if ("month".equals(selectStatus)) {
			param.put("status", "3");
		}

		PageInfo<Daily> pageInfo = new PageInfo<Daily>();
		try {
			pageInfo.setPageNo(page);
			pageInfo.setPageSize(limit);
			if (Strings.isNotEmpty(title)) {
				param.put("title", title);
			}
			json.put("flag", "0");
			PageInfo<Daily> pageRole = dailyService.getDailyList(param, pageInfo);
			json.put("total", pageRole.getPageCount());
			json.put("data", pageRole.getList());
			json.put("flag", "1");

		} catch (Exception e) {
			json.put("flag", "-1");
			logger.error("获取数据失败，原因：" + e);
		}
		return json;

	}

	/**
	 * 用户新增日报
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @param content
	 * @param title
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addDaily.do")
	@ResponseBody
	public Map<String, Object> addDaily(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			String content, String title, int status) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		// 获取当前用户
		Employee user = (Employee) session.getAttribute("loginUser");
		try {
			dailyService.saveDaily(user, content, title, status);
			json.put("code", 1);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 批阅汇报
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/readDaily.do")
	@ResponseBody
	public Map<String, Object> readDaily(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Daily daily) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		// 获取当前用户
		Employee user = (Employee) session.getAttribute("loginUser");
		try {
			daily.setReadStatus("1");
			daily.setReadEmpId(user.getEmployeeId());
			dailyService.updateDaily(daily);
			json.put("code", 0);
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", -1);
		}
		return json;
	}

	/**
	 * 通过id获取报表信息
	 * 
	 * @param response
	 * @param requset
	 * @param session
	 * @param id
	 *            报表id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getDailyListById.do")
	@ResponseBody
	public Map<String, Object> getDailyListById(HttpServletResponse response, HttpServletRequest requset,
			HttpSession session, String id) throws Exception {

		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Daily daily = dailyService.getDailyById(id);
			if (daily == null) {
				json.put("code", 0);
				json.put("msg", "数据出现异常,请稍后再试!");
			} else {
				json.put("code", 1);
				json.put("daily", daily);
			}
		} catch (Exception e) {
			json.put("code", -1);
			json.put("msg", "程序出错了!");
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 跳转用户详情界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userDetail.do")
	public ModelAndView customerDetail(String id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		if (id == null || id == "") {// 处理非法请求
			return new ModelAndView("/WEB-INF/jsp/error/404");
		}
		try {
			Employee user = (Employee) session.getAttribute("loginUser");
			user = employeeService.getEmployeeById(user.getEmployeeId().toString());
			request.setAttribute("user", user);
			return new ModelAndView("WEB-INF/jsp/user/userDetail");
		} catch (Exception e) {
			return new ModelAndView("/WEB-INF/jsp/error/500");
		}

	}

	/**
	 * 跳转首页
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/index.do")
	public ModelAndView toIndex(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		if (session.getAttribute("loginUser") != null) {
			return new ModelAndView("WEB-INF/jsp/index");
		}
		return new ModelAndView("/WEB-INF/jsp/error/404");
	}

	/**
	 * 获取员工信息
	 * 
	 * @param request
	 * @param limit
	 * @param page
	 * @param chanceName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryEmployeeList.do")
	@ResponseBody
	public Map<String, Object> queryEmployeeList(HttpServletRequest request, HttpSession session, Integer limit,
			Integer page, String name, String jstreeHeight, String jstreeId) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		PageInfo<Employee> pageInfo = new PageInfo<Employee>();
		Employee user = (Employee) request.getSession().getAttribute("loginUser");
		// 设置权限，如果menuId中有77员工通讯录的，则能看到所有员工信息
		Boolean canReadAllEmployee = checkPower(session, 77);
		Map<String, Object> map = new HashMap<String, Object>();
		if (name != null) {
			map.put("name", name);
		}
		// 拥有查看所有人的权限
		if (canReadAllEmployee) {
			if (("".equals(jstreeHeight) || jstreeHeight == null) && ("".equals(jstreeId) || jstreeId == null)) {
			} else if ("2".equals(jstreeHeight)) {
				map.put("remake", jstreeId);
			} else if ("3".equals(jstreeHeight)) {
				map.put("deptId", jstreeId);
			} else if ("4".equals(jstreeHeight)) {
				map.put("branchId", jstreeId);
			} else if ("5".equals(jstreeHeight)) {
				map.put("teamId", jstreeId);
			}
			pageInfo.setPageNo(page);
			pageInfo.setPageSize(limit);
			map.put("limit", limit);
			map.put("page", page);
			map.put("hasDept", 1);
			pageInfo = employeeService.getEmployeeList(map);

			json.put("total", pageInfo.getPageCount());
			json.put("data", pageInfo.getList());
			json.put("code", 1);

		} else {
			// 查询所有分公司部门团队
			List<ExportAllChartSales> deptBranchTeamList = departmentService.getDeptBranchTeam(null);
			Map<String, Object> branchByTeam = new HashMap<String, Object>();
			Map<String, Object> deptByTeam = new HashMap<String, Object>();
			Map<String, Object> deptByBranch = new HashMap<String, Object>();

			// 将团队部门分公司分别放到map中
			for (ExportAllChartSales deptBranchTeam : deptBranchTeamList) {
				if (deptBranchTeam.getTeamId() != null) {
					branchByTeam.put(deptBranchTeam.getTeamId(), deptBranchTeam.getBranchId());
					deptByTeam.put(deptBranchTeam.getTeamId(), deptBranchTeam.getDeptId());
				}
				if (deptBranchTeam.getBranchId() != null) {
					deptByBranch.put(deptBranchTeam.getBranchId(), deptBranchTeam.getDeptId());
				}
			}
			boolean canReadTeamByBranch = false;
			boolean canReadBranchByDept = false;
			if ("5".equals(jstreeHeight) && user.getTeam() == null && user.getBranch() != null
					&& branchByTeam.get(jstreeId) != null
					&& branchByTeam.get(jstreeId).equals(user.getBranch().getBranchId())) {
				canReadTeamByBranch = true;
			} else if ("5".equals(jstreeHeight) && user.getBranch() == null && deptByTeam.get(jstreeId) != null
					&& deptByTeam.get(jstreeId).equals(user.getDept().getDeptId())) {
				canReadTeamByBranch = true;
			} else if ("4".equals(jstreeHeight) && user.getBranch() == null && deptByBranch.get(jstreeId) != null
					&& deptByBranch.get(jstreeId).equals(user.getDept().getDeptId())) {
				canReadBranchByDept = true;
			}

			try {
				/*
				 * if (name != null) { map.put("name", name); }
				 */
				// 根据传过来树深度和id，执行查询
				if (("2".equals(jstreeHeight) && (jstreeId.equals(user.getDept().getRemake())))) {
					map.put("remake", user.getDept().getRemake());
					if (canReadTeamByBranch) {
						map.put("teamId", jstreeId);
					} else if (canReadBranchByDept) {
						map.put("branchId", jstreeId);
					} else {
						if (user.getDept() != null && user.getTeam() != null && user.getTeam().getBranchId() != ""
								&& user.getTeam().getBranchId() != null) {
							map.put("teamId", user.getTeam().getBranchId());
						} else if (user.getDept() != null && user.getBranch() != null
								&& user.getBranch().getBranchId() != "" && user.getBranch().getBranchId() != null) {
							map.put("branchId", user.getBranch().getBranchId());
						} else if (user.getDept() != null && user.getDept().getDeptId() != ""
								&& user.getDept().getDeptId() != null && canReadAllEmployee) {
							map.put("deptId", user.getDept().getDeptId());
						}
					}
				} else if (("3".equals(jstreeHeight) && user.getDept() != null
						&& (jstreeId.equals(user.getDept().getDeptId())))) {
					map.put("deptId", user.getDept().getDeptId());
					if (user.getDept() != null && user.getTeam() != null && user.getTeam().getBranchId() != ""
							&& user.getTeam().getBranchId() != null) {
						map.put("teamId", user.getTeam().getBranchId());
					} else if (user.getDept() != null && user.getBranch() != null
							&& user.getBranch().getBranchId() != "" && user.getBranch().getBranchId() != null) {
						map.put("branchId", user.getBranch().getBranchId());
					}

				} else if (canReadBranchByDept || (("4".equals(jstreeHeight) && user.getBranch() != null
						&& (jstreeId.equals(user.getBranch().getBranchId()))))) {
					if (canReadBranchByDept) {
						map.put("branchId", jstreeId);
					} else {
						map.put("branchId", user.getBranch().getBranchId());
						if (user.getDept() != null && user.getTeam() != null && user.getTeam().getBranchId() != ""
								&& user.getTeam().getBranchId() != null) {
							map.put("teamId", user.getTeam().getBranchId());
						}
					}
				} else if (canReadTeamByBranch || (("5".equals(jstreeHeight) && user.getTeam() != null
						&& jstreeId.equals(user.getTeam().getBranchId())))) {

					if (canReadTeamByBranch) {
						map.put("teamId", jstreeId);
					} else {
						map.put("teamId", user.getTeam().getBranchId());
					}

				} else {
					json.put("permission", "1");
				}

				if ((("".equals(jstreeHeight) || jstreeHeight == null) && ("".equals(jstreeId) || jstreeId == null))) {
					if (user.getDept() != null && user.getTeam() != null && user.getTeam().getBranchId() != ""
							&& user.getTeam().getBranchId() != null) {
						map.put("teamId", user.getTeam().getBranchId());
					} else if (user.getDept() != null && user.getBranch() != null
							&& user.getBranch().getBranchId() != "" && user.getBranch().getBranchId() != null) {
						map.put("branchId", user.getBranch().getBranchId());
					} else if (user.getDept() != null && user.getDept().getDeptId() != ""
							&& user.getDept().getDeptId() != null) {
						map.put("deptId", user.getDept().getDeptId());
					}
					json.put("permission", "");
				}

				if (!"1".equals(json.get("permission")) || (("".equals(jstreeHeight) || jstreeHeight == null)
						&& ("".equals(jstreeId) || jstreeId == null))) {
					pageInfo.setPageNo(page);
					pageInfo.setPageSize(limit);
					map.put("limit", limit);
					map.put("page", page);
					pageInfo = employeeService.getEmployeeList(map);

					json.put("total", pageInfo.getPageCount());
					json.put("data", pageInfo.getList());
					json.put("code", 1);
				} else {
					json.put("total", 0);
					json.put("data", pageInfo);
					json.put("code", 1);
				}
			} catch (Exception e) {
				logger.error("获取数据失败，原因：" + e);
				json.put("code", -1);
			}
		}
		return json;
	}

	/**
	 * 员工离职
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/dimissionEmployee.do")
	@ResponseBody
	public Map<String, Object> dimissionEmployee(HttpServletRequest request, HttpSession session, String empId) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			if (empId != null && empId != "") {
				Employee employee = new Employee();
				Employee user = (Employee) session.getAttribute("loginUser");
				employee.setUpdateEmpId(user.getEmployeeId());
				employee.setUpdateDate(new Date());
				employee.setEmployeeId(empId);
				employee.setStatus("2");
				employeeService.saveEmployee(employee, "修改");
				json.put("code", 1);
			} else {
				json.put("code", -2);
			}
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 通讯录详情查询
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/modifyEmployeeQuery.do")
	@ResponseBody
	public Map<String, Object> modifyEmployeeQuery(HttpServletRequest request, String id) {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			Employee employee = employeeService.getEmployeeById(id);
			if (employee == null) {
				json.put("flag", 0);
				json.put("msg", "数据出现异常,请稍后再试!");
			} else {
				json.put("flag", 1);
				json.put("employee", employee);
			}
		} catch (Exception e) {
			json.put("flag", -1);
			json.put("msg", "程序出错了!");
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 通讯录部门查询
	 * 
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping("/deptJsonQuery.do")
	@ResponseBody
	public Map<String, Object> deptJsonQuery(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) {
		// 返回数据json
		Map<String, Object> json = new HashMap<String, Object>();
		// 树第五层list，用来存放childrenMap数据
		List<Map<String, String>> finthFloorChildrenMapList = new ArrayList<>();
		// 树第四层list，用来存放childrenMap数据
		List<Map<String, Object>> fourthFloorChildrenMapList = new ArrayList<>();
		// 树第三层list，用来存放childrenMap数据
		List<Map<String, Object>> thirdFloorChildrenMapList = new ArrayList<>();
		// 树第二层list，用来存放childrenMap数据
		List<Map<String, Object>> secondFloorChildrenMapList = new ArrayList<>();
		// 树第一层Map
		Map<String, Object> firstFloorMap = new HashMap<String, Object>();
		// 树第一层list，用来存放childrenMap数据
		List<Map<String, Object>> firstFloorChildrenMapList = new ArrayList<>();
		Map<String, Object> coreMap = new HashMap<String, Object>();
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			// 将所有总公司统计、分公司统计、部门统计和团队统计查询出来
			List<Contacts> departmentList = departmentService.getContactsRemake(null);
			List<Contacts> deptNameList = departmentService.getContactsDept(null);
			List<Contacts> branchList = departmentService.getContactsBranch(null);
			List<Contacts> teamList = departmentService.getContactsTeam(null);
			// 员工总数
			int totalCountNum = 0;
			// 遍历总公司
			for (Contacts department : departmentList) {
				// 存放第三层的children数据
				thirdFloorChildrenMapList = new ArrayList<>();
				// 遍历部门department
				for (Contacts departmentInDeptNameList : deptNameList) {
					// 存放第四层的children数据
					fourthFloorChildrenMapList = new ArrayList<>();
					// 遍历Branch
					for (Contacts branch : branchList) {
						// 存放第五层children数据
						finthFloorChildrenMapList = new ArrayList<>();
						// 遍历团队team
						for (Contacts team : teamList) {
							if (team.getBranchId().equals(branch.getBranchId())) {
								Map<String, String> finthFloorMap = new HashMap<>();
								finthFloorMap.put("id", team.getTeamId());
								finthFloorMap.put("text", team.getBranchName() + "【" + team.getTotalNum() + "】");
								// 第五层list中添加第五层数据Map
								finthFloorChildrenMapList.add(finthFloorMap);
							}
						}
						Map<String, Object> fourthFloorMap = new HashMap<>();
						if (branch.getDeptId().equals(departmentInDeptNameList.getDeptId())) {
							fourthFloorMap.put("text", branch.getBranchName() + "【" + branch.getTotalNum() + "】");
							// 子树节点中添加id、children等
							fourthFloorMap.put("id", branch.getBranchId());
							fourthFloorMap.put("children", finthFloorChildrenMapList);
							fourthFloorChildrenMapList.add(fourthFloorMap);
						}
					}
					Map<String, Object> thirdFloorMap = new HashMap<String, Object>();
					if (department.getRemake().equals(departmentInDeptNameList.getRemake())) {
						// 将id放到分公司级别的节点上
						thirdFloorMap.put("id", departmentInDeptNameList.getDeptId());
						thirdFloorMap.put("text", departmentInDeptNameList.getDeptName() + "【"
								+ departmentInDeptNameList.getTotalNum() + "】");
						thirdFloorMap.put("children", fourthFloorChildrenMapList);
						thirdFloorChildrenMapList.add(thirdFloorMap);
					}
				}
				Map<String, Object> secondFloorMap = new HashMap<String, Object>();
				// 赋值到树节点
				secondFloorMap.put("id", department.getRemake());
				secondFloorMap.put("text", department.getRemake() + "【" + department.getTotalNum() + "】");
				secondFloorMap.put("children", thirdFloorChildrenMapList);
				secondFloorChildrenMapList.add(secondFloorMap);
				totalCountNum += department.getTotalNum();
			}
			// 设置默认展开第一层
			Map<String, Boolean> state = new HashMap<String, Boolean>();
			state.put("opened", true);
			firstFloorMap.put("state", state);
			// 树父节点设置为默认“滨海基金”
			firstFloorMap.put("text", "滨海基金" + "【" + totalCountNum + "】");
			firstFloorMap.put("children", secondFloorChildrenMapList);
			firstFloorChildrenMapList.add(firstFloorMap);
			coreMap.put("data", firstFloorChildrenMapList);
			returnMap.put("core", coreMap);

			json.put("returnMap", returnMap);
			json.put("flag", 1);
		} catch (Exception e) {
			json.put("flag", -1);
			json.put("msg", "程序出错了!");
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 响应验证码页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/validateCode.do")
	public String validateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		HttpSession session = request.getSession();

		ValidateCode vCode = new ValidateCode(120, 40, 5, 20);
		session.setAttribute("code", vCode.getCode());
		vCode.write(response.getOutputStream());
		return null;
	}

	/**
	 * 点击首页跳转界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/indexPage.do")
	public ModelAndView indexPage(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		return new ModelAndView("WEB-INF/jsp/indexPage");
	}

	/**
	 * 点击首页跳转界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toIndexManage.do")
	public ModelAndView toIndexManage(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		// if (checkPower(session, 110)) {
		// return new ModelAndView("WEB-INF/jsp/system/loginLogList");
		// } else {
		// return new ModelAndView("WEB-INF/jsp/error/404");
		// }
		return new ModelAndView("WEB-INF/jsp/indexManage");
	}

	/**
	 * 点击首页跳转界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toLoginLog.do")
	public ModelAndView toLoginLog(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		if (checkPower(session, 110)) {
			return new ModelAndView("WEB-INF/jsp/system/loginLogList");
		} else {
			return new ModelAndView("WEB-INF/jsp/error/404");
		}
	}

	/**
	 * 查询登录日志
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/loginLogQuery.do")
	@ResponseBody
	public Map<String, Object> loginLogQuery(Integer type, String device, String name, Integer page, Integer limit,
			HttpServletRequest request) {
		Map<String, Object> json = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("loginType", type);
			map.put("loginDevice", device);
			map.put("empName", name);
			map.put("pageNo", page);
			map.put("pageSize", limit);
			PageInfo<LoginLog> pageInfo = loginLogService.getPageInfoList(map);
			json.put("data", pageInfo.getList());
			json.put("total", pageInfo.getPageCount());
			;
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 生成菜单
	 * 
	 * @param oaMenu
	 * @param relation
	 * @return
	 */
	@SuppressWarnings("unused")
	private void shengcMenuSession(List<OaMenu> oaMenu, List<Relation> relation, HttpSession session) {
		for (OaMenu menu : oaMenu) {
			for (Relation rel : relation) {
				if (menu.getId() != null && rel.getOaMenu().getId().equals(menu.getId())) {
					if (menu.getId() == 46 || menu.getId() == 47 || menu.getId() == 48 || menu.getId() == 49
							|| menu.getId() == 59) {
						session.setAttribute("isPower", "1");
						return;
					}
				}
			}
		}
	}
}
